//
//  CLBookRecord.swift
//  CJBookReader
//
//  Created by colin on 2019/3/22.
//  Copyright © 2019 lidi. All rights reserved.
//

import UIKit

class CLBookRecord:Codable {
    var page = 0
    var chapter:CLBookChapter?
    
    init(page:Int,chapter:CLBookChapter?) {
        self.page = page
        self.chapter = chapter
    }
    
    // MARK: -- Codable
    private enum CodingKeys:String,CodingKey{
        case page
        case chapter
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(self.page, forKey: .page)
        try container.encode(self.chapter, forKey:.chapter)
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        for key in container.allKeys {
            switch key {
            case .page:
                self.page = try container.decodeNil(forKey: .page) ? 0 : try container.decode(Int.self, forKey: .page)
            case .chapter:
                self.chapter = try container.decodeNil(forKey: .chapter) ? nil : try container.decode(CLBookChapter.self, forKey: .chapter)
            }
        }
    }
    
    /// 深拷贝
    var copy:CLBookRecord? {
        do {
            let encoder = JSONEncoder()
            let encodedData = try encoder.encode(self)
            let decoder = JSONDecoder()
            let decodedObject = try decoder.decode(CLBookRecord.self, from: encodedData)
            return decodedObject
        } catch let err {
            print(err)
            return nil
        }
    }
    
}
